package ca.usask.cs.drawTree;

import com.nootropic.processing.layers.Layer;

import processing.core.PApplet;

public class HorizontalScrollbar extends Layer {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7995710931491407647L;
	int swidth, sheight; // width and height of bar
	int xpos, ypos; // x and y position of bar
	public float spos, newspos; // x position of slider
	int sposMin, sposMax; // max and min values of slider
	public int loose; // how loose/heavy
	boolean over; // is the mouse over the slider?
	boolean locked;
	float ratio;
	// DrawControler controler;
	static final int normalColor = 0xff993300;
	static final int seleteColor = 0xffFFFF00;
	public static float offset ;
	DrawControler controler;

	HorizontalScrollbar(int xp, int yp, int sw, int sh, int l, PApplet parent) {
		super(parent); // This is necessary!
		swidth = sw;
		sheight = sh;
		int widthtoheight = sw - sh;
		ratio = (float) sw / (float) widthtoheight;
		xpos = xp;
		ypos = yp - sheight / 2;
		spos = xpos + swidth / 2 - sheight / 2;
		newspos = spos;
		sposMin = xpos;
		sposMax = xpos + swidth - sheight;
		loose = l;
		controler = (DrawControler) parent;

	}

	void update() {
		if (over()) {
			over = true;

		} else {
			over = false;

		}
		if (parent.mousePressed && over && controler.VbarSeleted == false) {
			locked = true;
			controler.HbarSeleted = true;
		}
		if (!parent.mousePressed) {
			locked = false;
		}
		if (locked) {
			newspos = constrain1(parent.mouseX - sheight / 2, sposMin, sposMax);
		}
		if (parent.abs(newspos - spos) > 1) {
			spos = spos + (newspos - spos) / loose;
//			controler.rootx = spos - swidth / (float) 2;
//			controler.init = false;
			controler.HorizontalScrollBarUpdate((newspos - spos) / loose);
			offset = newspos - spos;
		//	parent.redraw();
		}
	}

	int constrain1(int val, int minv, int maxv) {
		return controler.min(controler.max(val, minv), maxv);
	}

	boolean over() {
		if (parent.mouseX > xpos && parent.mouseX < xpos + swidth
				&& parent.mouseY > ypos && parent.mouseY < ypos + sheight) {
			// System.out.println("true");
			return true;
		} else {
			return false;
		}
	}

	public void draw() {
		background(0, 0); // clear the background every time, but be transparent
		smooth();
		strokeWeight(2);
		fill(255);

		rect(xpos, ypos, swidth, sheight);
		if ((over || locked) && (controler.VbarSeleted == false)) {

			fill(seleteColor);
		} else {
			controler.HbarSeleted = false;
			fill(normalColor);
		}
		rect(spos, ypos, sheight + 10, sheight);

		update();

	}

	float getPos() {
		// Convert spos to be values between
		// 0 and the total width of the scrollbar
		return spos * ratio;
	}
}